import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient {
	public static void main(String[] args) throws IOException {
		while (true) {
			System.out.print("command>");
			char c = (char) System.in.read();
			System.in.read(); // read \n
			if (c == 'r') {
				singleRead();
			}
			else if (c == 'w') {
				singleWrite('a');
			}
		}
	}

	public static void singleWrite(char c) {
		try (Socket echoSocket = new Socket("localhost", 31039);
				OutputStream out = echoSocket.getOutputStream();
				InputStream in = echoSocket.getInputStream();) {
			System.out.print("input a char:");
			c = (char) System.in.read();
			System.in.read(); // \n
			out.write(c);
			echoSocket.close();
		} catch (UnknownHostException e) {
			System.out.println("Don't know about host " + "localhost");
			System.exit(1);
		} catch (IOException e) {
			System.out.println("Couldn't get I/O for the connection to "
					+ "localhost");
			System.exit(1);
		}
	}

	public static void singleRead() {
		try (Socket echoSocket = new Socket("localhost", 31039);
				OutputStream out = echoSocket.getOutputStream();
				InputStream in = echoSocket.getInputStream();) {
			byte a = (byte) 255;
			System.out.println("255 = " + a);
			out.write(a);
			char c;
			c = (char) in.read();
			System.out.println("read in " + c);
			echoSocket.close();
		} catch (UnknownHostException e) {
			System.out.println("Don't know about host " + "localhost");
			System.exit(1);
		} catch (IOException e) {
			System.out.println("Couldn't get I/O for the connection to "
					+ "localhost");
			System.exit(1);
		}
	}
}
